package com.basic.model.quartz.param;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.basic.model.quartz.handler.TaskHandler;
import com.basic.model.quartz.handler.TestTaskHandler;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;

@Data
public abstract class TaskParam {

    public static class Header {
        public String encode() {
            return JSONObject.toJSONString(this);
        }
    }

    @Data
    public static class Body {

        public String encode() {
            return JSONObject.toJSONString(this);
        }
    }

    @Builder
    @Data
    public static class KeyBuilder {
        private String name;
        private String group;

        public String toRedisKey() {
            return StrUtil.format("{}-{}", name, group);
        }
    }

    @Getter
    @AllArgsConstructor
    public static enum TaskType {
        TEST_TASK(1, "测试", TestTaskParam.class, TestTaskHandler.class),
        ;
        private int val;
        private String desc;
        private Class<? extends TaskParam> clazz;
        private Class<? extends TaskHandler> handler;

        public static TaskType valueOf(int val) {
            for (TaskType each: values()) {
                if (each.getVal() == val) {
                    return each;
                }
            }
            return null;
        }

    }

    protected Integer type;
    protected String header;
    protected String body;

    protected TaskParam(TaskType type, Header header, Body body) {
        this.type = type.getVal();
        if (header != null) {
            this.header = header.encode();
        }

        if (body != null) {
            this.body = body.encode();
        }
    }

    public abstract TaskParam.KeyBuilder getKeyBuilder();

    public abstract Integer getDelaySeconds();

    public Long getStartTime() {
        return System.currentTimeMillis();
    };

    public Body getBodyFormat() {
        if(body != null) {

            return JSONObject.parseObject(body, Body.class);
        }else {
            return null;
        }
    }

    public Header getHeaderFormat() {
        if(header != null) {

            return JSONObject.parseObject(header, Header.class);
        }else {
            return null;
        }
    }

    public TaskType getTaskTypeFormat() {
        return TaskType.valueOf(type);
    }

    public boolean isValid() {
        return this.type != null && this.body != null;
    }

    public String encode() {
        return JSONObject.toJSONString(this);
    }

    public static TaskParam decode(String value) {
        final JSONObject json = JSONObject.parseObject(value);
        return JSONObject.parseObject(value, TaskType.valueOf(json.getIntValue("type")).clazz);
    }

    public boolean isExpired() {
        return false;
    }

}
